package top.huntwolf.admin.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.show.api.ShowApiRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.dao.CMSBookDao;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.pojo.book.Book;
import top.huntwolf.admin.pojo.book.BuyBook;
import top.huntwolf.admin.utils.RedisUtil;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CMSBookService {

    @Autowired
    private CMSBookDao cmsBookDao;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BookStorageService storageService;

    @Autowired
    private BookReserveService reserveService;

    @Value("${showApi.url1}")
    private String url1;

    @Value("${showApi.url2}")
    private String url2;

    @Value("${showApi.appid}")
    private String appid;

    @Value("${showApi.secret}")
    private String secret;


    public int searchBookStock(){
        int total_inventory = 0;
        Object stock = redisUtil.get("Total inventory");
        if(stock != null)
            total_inventory = (Integer) stock;

        return total_inventory;
    }

    public PageInfo<BuyBook> searchBookInfoByCMS(int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<BuyBook> buyBooks = cmsBookDao.selectBookInfo();
        PageInfo<BuyBook> pageInfo = new PageInfo<>(buyBooks);
        return pageInfo;
    }

    public PageInfo<BuyBook> searchBookInfoByIsbn(String isbn,int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<BuyBook> buyBooks = cmsBookDao.selectBookInfoByIsbn(isbn);
        PageInfo<BuyBook> pageInfo = new PageInfo<>(buyBooks);
        return pageInfo;
    }

    public PageInfo<BuyBook> searchBookInfoByAuthor(String author,int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<BuyBook> buyBooks = cmsBookDao.selectBookInfoByAuthor(author);
        PageInfo<BuyBook> pageInfo = new PageInfo<>(buyBooks);
        return pageInfo;
    }

    public PageInfo<BuyBook> searchBookInfoByTitle(String author,int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<BuyBook> buyBooks = cmsBookDao.selectBookInfoByTitle(author);
        PageInfo<BuyBook> pageInfo = new PageInfo<>(buyBooks);
        return pageInfo;
    }

    public void updateBookSubject(List<BuyBook> books) {
        int res = cmsBookDao.updateSubject(books);
        if(res<=0){
            throw new ServiceException(CodeMsg.BOOK_UPDATE_FAIL);
        }
    }

    public List<Book> searchBookIsbnAndTitle() {
        return cmsBookDao.selectAllBookPartInfo();
    }

    public PageInfo<BuyBook> searchBookInfoBySubjectId(String subjectId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<BuyBook> buyBooks = cmsBookDao.selectBookInfoBySubjectId(subjectId);
        PageInfo<BuyBook> pageInfo = new PageInfo<>(buyBooks);
        return pageInfo;
    }

    public void addBuyBookByISBN(BuyBook book){
        if(cmsBookDao.selectBookByISBN(book.getIsbn()) == null ){
            if(book.getGist().length()>1000){
                throw new ServiceException(CodeMsg.GIST_TOO_LONG.fillArgs("不能超过1000字"));
            }
            book.setCreateTime(new Date());
            if(book.getSearchTime()==null){
                book.setSearchTime(0);
            }
            if(book.getSaleVolume()==null){
                book.setSaleVolume(0);
            }
            cmsBookDao.insert(book);
        }

        Integer sum = storageService.addBookStorage(book.getBookStorages());
        reserveService.addBookReserve(book,sum);
    }

    // 调用易源Api直接查询书本的属性
    public BuyBook getBookDetailsFromApi(String isbn) {

        BuyBook newBook = cmsBookDao.selectBookByISBN(isbn);
        if (newBook!=null){
            throw new ServiceException(CodeMsg.REPEATED_BOOK);
        }
        String res = new ShowApiRequest(url1, appid, secret)
                .addTextPara("isbn", isbn)
                .post();
        JSONObject resJson = JSON.parseObject(res);
        if (resJson.get("showapi_res_code").equals(0)) {
            //请求成功
            if (!resJson.getJSONObject("showapi_res_body").getString("ret_code").equals("0")) {
                //api1失败时调用api2
                return getBookDetailsFromApi2(isbn);
            }
        }
        BuyBook book = new BuyBook();
//        封装属性
        JSONObject resBook = resJson.getJSONObject("showapi_res_body").getJSONArray("datas").getJSONObject(0);
        book.setIsbn(isbn);
        book.setSeries(resBook.getString("series"));
        book.setTitle(resBook.getString("title"));
        book.setImg(resBook.getString("img"));
        book.setSmallImg(resBook.getString("smallimg"));
        book.setPrice(resBook.getString("price"));
        book.setAuthor(resBook.getString("author"));
        book.setPublisher(resBook.getString("publisher"));
        book.setPubDate(resBook.getString("pubdate"));
        book.setPubPlace(resBook.getString("pubplace"));
        book.setBinding(resBook.getString("binding"));
        book.setGenus(resBook.getString("genus"));
        book.setFormat(resBook.getString("format"));
        book.setPage(resBook.getString("page"));
        book.setWordNum(resBook.getString("wordnum"));
        book.setEdition(resBook.getString("edition"));
        book.setYinci(resBook.getString("yinci"));
        book.setPaper(resBook.getString("paper"));
        book.setLanguage(resBook.getString("language"));
        book.setKeyword(resBook.getString("keyword"));
        book.setBookCatalog(resBook.getString("bookcatalog"));
        book.setGist(resBook.getString("gist"));
        book.setCipTxt(resBook.getString("ciptxt"));
        book.setSearchTime(1);
        book.setCreateTime(new Date());
        book.setSaleVolume(0);
        return book;

    }

    public BuyBook getBookDetailsFromApi2(String isbn) {

        String res = new ShowApiRequest(url2, appid, secret)
                .addTextPara("isbn", isbn)
                .post();
        JSONObject resJson = JSON.parseObject(res);
        if (resJson.get("showapi_res_code").equals(0)) {
            //请求成功
            if (!resJson.getJSONObject("showapi_res_body").getString("ret_code").equals("0")) {
                String remark = resJson.getJSONObject("showapi_res_body").getString("remark");
                throw new ServiceException(CodeMsg.SHOWAPI_ERROR.fillArgs(remark));
            }
        }
        BuyBook book = new BuyBook();
//        封装属性
        JSONObject resBook = resJson.getJSONObject("showapi_res_body").getJSONObject("data");
        book.setIsbn(isbn);
        book.setTitle(resBook.getString("title"));
        book.setImg(resBook.getString("img"));
        book.setPrice(resBook.getString("price"));
        book.setAuthor(resBook.getString("author"));
        book.setPublisher(resBook.getString("publisher"));
        book.setPubDate(resBook.getString("pubdate"));
        book.setBinding(resBook.getString("binding"));
        book.setFormat(resBook.getString("format"));
        book.setPage(resBook.getString("page"));
        book.setEdition(resBook.getString("edition"));
        book.setPaper(resBook.getString("paper"));
        book.setGist(resBook.getString("gist"));
        book.setSearchTime(1);
        book.setCreateTime(new Date());
        book.setSaleVolume(0);
        return book;

    }
}